﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GameLib.Utils;

namespace GameLib.Serialization
{
	public class DataType
	{
		public Name Name
		{
			get;
			private set;
		}

		public override string ToString()
		{
			return string.Format("DataType<{0}>", Name);
		}

		public static DataType Register(string name, string[] extensions)
		{
			name = name.ToUpper();

			if (DataTypes.ContainsKey(name))
				throw new Exception(string.Format("Attempting register the Data type with name {0} more than once!", name));

			DataType dataType = new DataType(Name.FromString(name));
			DataTypes[name] = dataType;

			if (extensions != null)
			{
				foreach (string ext in extensions)
				{
					string internalExt = ext.ToUpper();

					if (ExtToDataTypes.ContainsKey(internalExt))
						throw new Exception(string.Format("Extension {0} has been registered with {1}, but now attempting register with {2}", internalExt, ExtToDataTypes[internalExt], dataType));

					ExtToDataTypes[internalExt] = dataType;
				}
			}

			return dataType;
		}

		public static DataType FindDataType(string name)
		{
			DataType dataType;
			if (DataTypes.TryGetValue(name.ToUpper(), out dataType))
				return dataType;
			else
				return null;
		}

		public static DataType FindDataTypeByExt(string extension)
		{
			DataType dataType;
			if (DataTypes.TryGetValue(extension.ToUpper(), out dataType))
				return dataType;
			else
				return null;
		}

		private static Dictionary<string, DataType> ExtToDataTypes = new Dictionary<string, DataType>();
		private static Dictionary<string, DataType> DataTypes = new Dictionary<string, DataType>();

		private DataType(Name name)
		{
			Name = name;
		}
	}
}
